<?php
abstract class BaseController extends BaseControl
{
	protected $action;
	protected $layout;
    protected $useLayout = true;
    protected $title;
    protected $metaKeywords;
    protected $metaDescription;
    protected $cache;
    protected $params;

    public function BaseController()
    {
        $this->CheckPermission();
        $this->name = $this->GetClassName();
        $this->underscoreName = $this->GetUnderscoreName();
        $this->config = $this->GetConfig();
        $this->title = String::CropEnd('Controller', $this->name).' '. $this->action;
        if ($this->useLayout) $this->layout = $this->GetLayout();
    }

    protected function GetLayout()
    {
        return new BlankLayout();
    }

    public function GetTemplatePath()
    {
        return $this->config->DIR_HTML_CONTROLLERS.DS.$this->underscoreName;
    }

    public function GetElementPath()
    {
        return $this->GetTemplatePath().DS.'elements';
    }

    public function SetAction($action)
    {
    	$this->action = String::Pascalize($action);
    	try
    	{
        	$this->SetTemplate();
		}
		catch(Exception $ex) // template file not found
		{
			$this->template = null;
		}
    }

    public function SetParams($params)
    {
        $this->params = $params;
    }

    protected function SetTemplate($template_file = null)
    {
    	if (!$template_file) $template_file = "{$this->action}.html";
    	$this->template = new Template($template_file, $this->GetTemplatePath());
    }

    protected function GetUnderscoreName()
    {
        return String::CropEnd('_controller', String::Underscore($this->name));
    }

    public function Render($content = null, $layout = null)
    {
        $content = $this->RenderNoLayout($content);
        if ($this->useLayout)
        {
            if (is_null($layout)) $layout = $this->layout;
            $this->ReplaceLayout('title', $this->title);
            $this->ReplaceLayout('meta_keywords', $this->metaKeywords);
            $this->ReplaceLayout('meta_description', $this->metaDescription);
            return $layout->Render($content);
        }
        else return $content;
    }

    public function RenderNoLayout($content = null)
    {
        return is_null($content) ? $this->GetContent() : $content;
    }

    protected function GetContent()
    {
    	try
    	{
            return $this->GetTemplate()->Render();
		}
		catch(Exception $ex){}
    }

	public function ReplaceLayout($key, $value = null)
	{
        if (is_object($value)) $value = $value->Render();
		return $this->layout->Replace($key, $value);
	}

	public function RepeatLayout($zone, $data, $callback = null)
	{
		return $this->layout->Repeat($zone, $data, $callback);
	}

    protected function SetFileHeader($file_name, $file_type)
    {
        $file_name = AppConfig::GetInstance()->APP_PREFIX.$file_name;
        header("Content-Type: $file_type");
        header("Content-Disposition: attachment; filename=\"$file_name\"");
    }

    public function RenderFile($file_name, $file_type, $file_content)
    {
        $this->SetFileHeader($file_name, $file_type);
        return $this->RenderNoLayout($file_content);
    }

    protected function CheckPermission()
    {
        if (!$this->resourceId) return;
        $config = AppConfig::GetInstance();
        $userModel = $config->GetUserModel();
        if (!$userModel) return;
        if (!$userModel->IsLoggedIn())
        {
            RequestHandler::Redirect($config->URL_LOGIN.'?ref='.urlencode($_SERVER['REQUEST_URI']));
        }
        else
        {
            try
            {
                $user_id = $userModel->GetCurrentUserId();
                AclPermissionModel::Authorize($user_id, $this->resourceId, 'view');
            }
            catch (NoPermissionException $ex)
            {
                RequestHandler::Redirect($config->URL_UNAUTHORIZED);
            }
        }
    }

    public function RenderPage()
    {
        $this->cache = new CacheHtml(RequestHandler::GetInstance()->url);
        return $this->RenderCache();
    }

    protected function DoRenderPage()
    {
        if (RequestHandler::GetInstance()->subUrl)
        {
            $out = $this->RenderSubRequest();
        }
        else
            $out = call_user_func_array(array($this, $this->action), $this->params);
        return $this->Translate($out);
    }

    public function RenderSubRequest()
    {
        $subs = explode(FS, RequestHandler::GetInstance()->subUrl);
        $reflect = new ReflectionClass($subs[0]);
        if ($reflect->isSubclassOf('BaseControl'))
        {
            $params = Set::Shift($subs, 1);
            $control = $reflect->newInstanceArgs($params);
            return $control->ProcessRequest();
        }
    }

    protected function RenderCache()
    {
        if ($this->cache->IsValid())
            $out = $this->cache->Render();
        else
        {
            $out = $this->DoRenderPage();
            $this->cache->Save($out);
        }
        return $out;
    }

    public function SetTitle($title)
    {
        $this->title = $title;
    }

    public function SetMetaKeywords($metaKeywords)
    {
        $this->metaKeywords = $metaKeywords;
    }

    public function SetMetaDescription($metaDescription)
    {
        $this->metaDescription = $metaDescription;
    }

    protected function Translate($out)
    {
//        if (AppConfig::GetInstance()->LANGUAGE_TRANSLATE_MODE
//        && $this->resourceId != 'AdminResource'
//        && $this->resourceId != 'SystemResource')
//            $out = CmsDictionaryModel::GetInstance()->Translate($out, AppConfig::GetInstance()->GetLanguageId());
        return $out;
    }
}
?>
